<?php

namespace Home\Controller;

use Carbon\Carbon;  //获取当前创建时间
use Org\Util\FileUploadHandler;
use Think\Exception;  //抛出异常
use Think\Upload;   //上传文件

class MeetingsController extends AuthController
{
    protected $ITManager = 1789;   //管理员

    public function index($tab = '')
    {
        if (!$tab) redirect('/meetings?tab=list');

        $now_time = Carbon::now()->toDateTimeString(); //当前时间
        $sessionId = session('user')['id'];

        //筛选
        $conditions = I('get.');
        if ($conditions['title']) {
            $map['title'] = ['LIKE', "%{$conditions['title']}%"];
            $map_all['atop_meetings.title'] = ['LIKE', "%{$conditions['title']}%"];
        }
        if ($conditions['start']) {
            $map['start_time'] = ['egt', "{$conditions['start']}"];
            $map_all['atop_meetings.start_time'] = ['egt', "{$conditions['start']}"];
        }
        if ($conditions['end']) {
            $map['end_time'] = ['elt', "{$conditions['end']} . '23:59:59'"];
            $map_all['atop_meetings.end_time'] = ['elt', "{$conditions['end']} . '23:59:59'"];
        }
        if ($conditions['create']) {
            $map['user_id'] = ['eq', "{$conditions['create']}"];
            $map_all['atop_meetings.user_id'] = ['eq', "{$conditions['create']}"];
        }
        if ($conditions['status'] == 1)
        {
            $map['status'] = ['eq', 0];
            $map_all['atop_meetings.status'] = ['eq', 0];
            $map['start_time'] = ['egt', "{$now_time}"];
            $map_all['atop_meetings.start_time'] = ['egt', "{$now_time}"];
        }
        if ($conditions['status'] == 2)
        {
            $map['status'] = ['eq', 0];
            $map_all['atop_meetings.status'] = ['eq', 0];
            $map['start_time'] = ['elt', "{$now_time}"];
            $map_all['atop_meetings.start_time'] = ['elt', "{$now_time}"];
            $map['end_time'] = ['egt', "{$now_time}"];
            $map_all['atop_meetings.end_time'] = ['egt', "{$now_time}"];
        }
        if ($conditions['status'] == 3)
        {
            $map['status'] = ['eq', 0];
            $map_all['atop_meetings.status'] = ['eq', 0];
            $map['end_time'] = ['elt', "{$now_time}"];
            $map_all['atop_meetings.end_time'] = ['elt', "{$now_time}"];
        }
        if ($conditions['status'] == -1)
        {
            $map['status'] = ['eq', -1];
            $map_all['atop_meetings.status'] = ['eq', -1];
        }

        //我申请的
        $applyCount = M('Meetings')->where("user_id={$sessionId}")->count();
        if ($tab == 'apply') {
            $lists = D('Meetings')->inquireMyMeetings($sessionId,$now_time,'create',$map);
            $applyCount = $lists[2];
        }

        //我参加的
        $participateCount = M('Meetings')->where("find_in_set({$sessionId},participants)")->count();
        if ($tab == 'participate') {
            $lists = D('Meetings')->inquireMyMeetings($sessionId,$now_time,'participate',$map);
            $participateCount = $lists[2];
        }

        //我能看到的所有会议
        $meetings = D('Meetings')->field(['atop_meetings.*','group_concat(atop_meeting_rooms.auth_group)'=>'auth_group'])
            ->join("atop_meeting_rooms ON find_in_set(atop_meeting_rooms.id,atop_meetings.meeting_room_id)")
            ->group('atop_meetings.id')
            ->select();
        foreach ($meetings as &$meeting)
        {
            if (D('Meetings')->isShow($meeting['id']))
            {
                $data[] = $meeting;
            }
        }
        $allCount = count($data);
        if ($tab == 'list') {
            $lists = D('Meetings')->inquireMyMeetings($sessionId,$now_time,'all',$map_all);
            $allCount = $lists[2];
        }

        //数据和分页
        $list = $lists[0];
        $page = $lists[1];
        $Page = $page->show();

        //用户
        $users = D('User')->scope('office')->select();
        $this->assign('users',$users);

        $this->assign('list', $list);
        $this->assign('applyCount', $applyCount);
        $this->assign('participateCount', $participateCount);
        $this->assign('allCount', $allCount);
        $this->assign('Page',$Page);
        $this->display();
    }

    public function show($id)
    {
        //权限（只有特殊授权及IT管理员以及参会人员、申请人能够看到）
        $isShow = D('Meetings')->isShow($id);
        if (!$isShow)
        {
            $this->assign('PERMISSION_DENIED', true);
            $this->display();
            return false;
        }

        $details = D('Meetings')->relation(['user','host_detail','recorder_detail'])->find($id);
        $details['rooms'] = M('MeetingRooms')->field(['name'])->where("id in ({$details['meeting_room_id']})")->select();  //会议室
        $details['participants_detail'] = M('User')->field(['id','nickname, face'])->where("id in ({$details['participants']})")->select();  //参会人员
        $now_time = Carbon::now()->toDateTimeString(); //当前时间

        //附件格式转换
        $details['meeting_files'] = json_decode($details['meeting_files'], true);
        $details['summary_files'] = json_decode($details['summary_files'], true);

        //时间格式转换
        $details['time_status'] = D('Meetings')->changeStatus($details['start_time'],$details['end_time'],$now_time);
        $details['year'] = D('Meetings')->changeTime($details['start_time'],4);
        $details['start'] = D('Meetings')->changeTime($details['start_time'],2);
        $details['end'] = D('Meetings')->changeTime($details['end_time'],2);

        //会议纪要只能参会人员、申请人、特殊授权才能看到
        $showSummary = $isShow = D('Meetings')->isShow($id,1);

        $this->assign('details', $details);
        $this->assign('ITManager', $this->ITManager);
        $this->assign('showSummary', $showSummary);
        $this->display();
    }

    public function create()
    {
        $users = D('User')->scope('office')->select();
        $rooms = M('MeetingRooms')->field('id,name')->where("status=0")->select();
        $this->assign('rooms',$rooms);
        $this->assign('users',$users);
        $this->display();
    }

    public function edit($id)
    {
        $meeting = M('Meetings')->find($id);

        //只有创建者和IT管理员才能访问
        $isAuthor = D('Meetings')->isAuthor($meeting['user_id']);
        $isITManager = D('Meetings')->isManager();
        if (!($isAuthor || $isITManager))
        {
            $this->assign('PERMISSION_DENIED', true);
            $this->display();
            return false;
        }

        //时间格式
        $meeting['start_time'] = D('Meetings')->changeTime($meeting['start_time'],3);
        $meeting['end_time'] = D('Meetings')->changeTime($meeting['end_time'],3);

        // 获得会议室详细信息
        if (!empty($meeting['meeting_room_id'])) {
            $map['id'] = ['in', $meeting['meeting_room_id']];
        } else {
            throw new Exception('非法访问');
        }
        $meeting['datas'] = M('MeetingRooms')->field(['id, name, location, seats, type, pic'])->where($map)->select();

        //附件格式转换
        $meeting['meeting_files'] = json_decode($meeting['meeting_files'], true);

        $now_time = Carbon::now()->toDateTimeString(); //当前时间

        //分别获取会议室预约情况
        $meeting['datas'] = D('Meetings')->inquireReservation($meeting['datas'],$now_time,$id); //编辑时的预约状态不包含编辑的会议

        $users = D('User')->scope('office')->select();
        $rooms = M('MeetingRooms')->field('id,name')->select();
        $this->assign('rooms',$rooms);
        $this->assign('users',$users);
        $this->assign('meeting', $meeting);
        $this->display();
    }

    public function rooms()
    {
        $now_time = Carbon::now()->toDateTimeString();

        //数据分页
        $count = M('MeetingRooms')->where("status=0")->count();
        $page = D('Meetings')->getPage($count,3);

        $rooms = D('MeetingRooms')->relation(['user'])->where("status=0")->limit($page->firstRow . ',' . $page->listRows)->select(); //关联user表
        $page = $page->show();

        //room的会议
        foreach ($rooms as &$room)
        {
            $room['meetings']['details'] = D('Meetings')->relation(['user'])->field(['id','title','user_id','start_time','end_time','status'])
                ->where("find_in_set({$room['id']},meeting_room_id)")->order('start_time desc')->select();

            //改变时间格式和状态
            foreach ($room['meetings']['details'] as &$detail)
            {
                $detail['start'] = D('Meetings')->changeTime($detail['start_time'],3);
                $detail['end'] = D('Meetings')->changeTime($detail['end_time'],2);
                $detail['time_status'] = D('Meetings')->changeStatus($detail['start_time'],$detail['end_time'],$now_time);
            }
        }

        $this->assign('ITManager',$this->ITManager);
        $this->assign('rooms', $rooms);
        $this->assign('page', $page);
        $this->display();
    }

    public function createMeetingRoom()
    {
        //开放给IT管理员
        $isITManager = D('Meetings')->isManager();
        if (!$isITManager) {
            $this->assign('PERMISSION_DENIED', true);
        }

        //特殊授权角色
        $posts = M('Position')->field(['id', 'name'])->order('convert(name using gbk)')->select();
        $this->assign('posts', $posts);
        $this->display();
    }

    public function editMeetingRoom($id)
    {
        //开放给IT管理员
        $isITManager = D('Meetings')->isManager();
        if (!$isITManager) {
            $this->assign('PERMISSION_DENIED', true);
        }

        $room = M('MeetingRooms')->find($id);
        $this->assign('room', $room);

        //特殊授权角色
        $posts = M('Position')->field(['id', 'name'])->order('convert(name using gbk)')->select();
        $this->assign('posts', $posts);

        $this->display();
    }

    //会议纪要文本框中图片上传接口
    public function uploadImage()
    {
        $imgUploader = new FileUploadHandler();
        $this->ajaxReturn($imgUploader->simditorSave('images'));
    }

    //会议纪要和会议相关附件上传接口
    public function uploadFiles()
    {
        $key = 'file';
        $config = [
            'rootPath' => './Uploads/',
            'maxSize' => 10485760,
            'savePath' => 'Meetings/Summaries/',
            'autoSub' => false,
            'exts' => ['zip', 'rar', 'jpg', 'png', 'jpeg', 'doc', 'xls', 'gif', 'xlsx', 'docx', 'pdf'],
            'saveName' => time() . '_' . uniqid() . '_' . generateRandomString(),
        ];

        $upload = new Upload($config);
        $result = $upload->upload();

        if ($result) {
            $path = C('APP_URL') . '/Uploads/'.$result[$key]['savepath'].$result[$key]['savename'];
            $name = $result[$key]['name'];
            $savename = $result[$key]['savename'];
            $ext = strtolower($result[$key]['ext']);
            $mime = $result[$key]['type'];
            $size = $result[$key]['size'];
            $time = time();

            $data = [
                'code' => 0,
                'data' => [
                    'path' => $path,
                    'name' => $name,
                    'ext' => $ext,
                    'savename' => $savename
                ]
            ];
        } else {
            $data = [
                'code' => 1,
                'msg' => $upload->getError()
            ];
        }

        $this->ajaxReturn($data);
    }

    //会议纪要保存接口
    public function meetingSummaryStore()
    {
        try {
            if (!IS_POST) throw new Exception('非法请求');
            $po = I('post.');

            M()->startTrans();/*事务 影响到多张表的数据*/

            $now_time = Carbon::now()->toDateTimeString();
            $po['summary_created_at'] = $now_time;  //录入会议纪要时间
            $session = session('user');

            //附件转换为数组形式
            $i = 0;
            foreach ($po['files'] as &$file) {
                $summary_files[$i]['path'] = $file['path'];
                $summary_files[$i]['ext'] = $file['ext'];
                $summary_files[$i]['name'] = $file['name'];
                $summary_files[$i]['savename'] = $file['savename'];
                $i++;
            }
            $po['summary_files'] = json_encode($summary_files);  //转为json格式存储

            M('Meetings')->save($po);

            //写入通知消息（告诉所有参会人员该会议纪要已创建可去阅读）
            $post = M('Meetings')->find($po['id']);
            $host = M('User')->field(['id', 'nickname' => 'name'])->find($post['host']);
            $recorder = M('User')->field(['id', 'nickname' => 'name'])->find($post['recorder']);
            $post['start_time'] = D('Meetings')->changeTime($post['start_time'],3);
            $post['end'] = D('Meetings')->changeTime($post['end_time'],2);
            $participants = explode(',',$post['participants']);
            foreach ($participants as &$participant)
            {
                M('Messages')->add([
                    'title' => '[会议]《' . $post['title'] . '》会议纪要',
                    'abstract' => $session['nickname'] . '创建了在 ' . $post['start_time'] . ' 至 ' . $post['end'] . ' 召开的《' . $post['title'] . '》' . '的会议纪要，请查看。',
                    'module_name' => 'meetings',
                    'url' => '/meetings/show?id=' . $po['id'],
                    'created_at' => time(),
                    'created_user' => $session['id'],
                    'target_user' => $participant,
                ]);
            }

            //清除其待办事项并写入完成时间
            $head = C('WEB_SITE');
            $map = "who = {$post['recorder']} and url = '{$head}/meetings/show?id={$po['id']}' ";
            M('Todolist')->where($map)->save([
                'complete_time' => time(),
                'state' => 'done'
            ]);

            //邮件信息
            $joins = D('User')->scope('basic')->field(['id', 'nickname' => 'name', 'email'])
                ->where("`id` in ({$post['participants']}) and `id`<>{$session['id']}")->select();
            $join = D('User')->scope('basic')->field(['id', 'nickname' => 'name', 'email'])
                ->where("`id` in ({$post['participants']})")->select();
            $joinCount = count($join);
            $user = M('User')->field(['id', 'nickname' => 'name'])->find($session['user_id']);
            $url = C('APP_URL') . '/meetings/show?id=' . $po['id'] ;
            $room = M('MeetingRooms')->field(['name'])->where("id in ({$post['meeting_room_id']})")->select(); //会议室
            $count = count($room); //会议室个数
            $type = 'record';
            $this->template('Meetings/_email',
                compact('user', 'url', 'post', 'room', 'count', 'host', 'recorder', 'type', 'join', 'joinCount'))
                ->subject('[会议]《' . $post['title'] . '》会议纪要')
                ->to($joins)->cc([
                    ['name' => $session['nickname'], 'email' => $session['email']]
                ])->send();

            M()->commit(); /*事务 影响到多张表的数据*/

        } catch (Exception $exception) {

            M()->rollback(); /*事务 影响到多张表的数据*/

            $this->api['code'] = 1;
            $this->api['msg'] = $exception->getMessage();
        }

        $this->ajaxReturn($this->api);
    }

    //meeting的会议室选择后信息展示接口
    public function meetingRoomShow()
    {
        try {
            if (!IS_POST) throw new Exception("非法请求！");
            $post = I('post.');
            if ($post['meeting_id'])
            {
                $id = $post['meeting_id'];
            } else {
                $id = 0;
            }

            //如果提交的id为空则不进行查询
            if (!empty($post['id'])) {
                $map['id'] = ['in', $post['id']]; //含表达式查询条件（in 表示判断id是否在一个范围里，如(30,65),一行数据为单位）
                $now_time = Carbon::now()->toDateTimeString(); //当前时间
                $data = M('MeetingRooms')->field(['id, name, location, seats, type, pic'])->where($map)->select();

                //该会议室的预约情况
                $data = D('Meetings')->inquireReservation($data,$now_time,$id);
                $this->api['data'] = $data;
            }
        } catch (Exception $exception) {
            $this->api['code'] = 1;
            $this->api['msg'] = $exception->getMessage();
        }

        $this->ajaxReturn($this->api);
    }

    //meeting的保存编辑接口
    public function meetingStore()
    {
        try {
            if (!IS_POST) throw new Exception("非法请求！");
            $post = I('post.');
            $now_time = Carbon::now()->toDateTimeString(); //当前时间
            $session = session('user');

            //邮件信息
            $joins = D('User')->scope('basic')->field(['id', 'nickname' => 'name', 'email'])
                ->where("`id` in ({$post['participants']}) and `id`<>{$session['id']}")->select();//参会人员除去申请人
            $join = D('User')->scope('basic')->field(['id', 'nickname' => 'name', 'email'])
                ->where("`id` in ({$post['participants']})")->select();
            $joinCount = count($join);
            $user = M('User')->field(['id', 'nickname' => 'name'])->find($session['id']);  //申请人
            $host = M('User')->field(['id', 'nickname' => 'name'])->find($post['host']);   //主持人
            $recorder = M('User')->field(['id', 'nickname' => 'name'])->find($post['recorder']);   //纪要员
            $room = M('MeetingRooms')->field(['name'])->where("id in ({$post['meeting_room_id']})")->select(); //会议室
            $count = count($room); //会议室个数


            //防止会议时间冲突
            $rooms = explode(',',$post['meeting_room_id']);

            M()->startTrans();//开始事务

            //编辑时入口
            if (isset($post['id'])) {
                $id = $post['id'];

                //防止会议时间冲突
                $type = D('Meetings')->inquireAllTime($rooms,$post['start_time'],$post['end_time'],$id);
                if ($type == 1) throw new Exception('会议时间冲突，该时间段已有其他会议被预约');

                $old = M('Meetings')->field(['start_time, title, end_time'])->find($id);
                $old['start_time'] = D('Meetings')->changeTime($old['start_time'],3);
                $old['end_time'] = D('Meetings')->changeTime($old['end_time'],2);

                $post['updated_at'] = $now_time;  //编辑时间
                $post['updated_user_id'] = $session['id'];  //编辑操作人id

                //附件转换为数组形式
                $i = 0;
                foreach ($post['files'] as &$file) {
                    $meeting_files[$i]['path'] = $file['path'];
                    $meeting_files[$i]['ext'] = $file['ext'];
                    $meeting_files[$i]['name'] = $file['name'];
                    $meeting_files[$i]['savename'] = $file['savename'];
                    $i++;
                }
                $post['meeting_files'] = json_encode($meeting_files);  //转为json格式存储

                M('Meetings')->save($post);

                //写入通知中心
                $participants = explode(',',$post['participants']);
                $old['start_time'] = D('Meetings')->changeTime($old['start_time'],3);
                $old['end_time'] = D('Meetings')->changeTime($old['end_time'],2);
                foreach ($participants as &$participant)
                {
                    M('Messages')->add([
                        'title' => '[会议]《' . $old['title'] . '》会议修改',
                        'abstract' => '原计划将在 ' .  $old['start_time'] . ' 至 ' . $old['end_time'] . ' 进行的《' . $old['title'] . '》的会议信息被修改了，请你查看并准时参加。',
                        'module_name' => 'meetings',
                        'url' => '/meetings/show?id=' . $id,
                        'created_at' => time(),
                        'created_user' => $session['id'],
                        'target_user' => $participant,
                    ]);
                }

                //会议纪要员的待办事项重新写入并删除之前的
                $head = C('WEB_SITE');
                M('Todolist')->where("url = '{$head}/meetings/show?id={$id}'")->delete();
                M('Todolist')->add([
                    'from_user_id' => $session['id'],
                    'who' => $post['recorder'],
                    'module' => 'meetings',
                    'matter_name' => '[会议] ' . '请在《' . $post['title'] . '》的会议结束后及时写入相关会议纪要',
                    'url' => $head . '/meetings/show?id=' . $id,
                    'generate_time' => time()
                ]);

                //编辑会议时邮件通知
                $post['start_time'] = D('Meetings')->changeTime($post['start_time'],3);
                $post['end'] = D('Meetings')->changeTime($post['end_time'],2);
                $url = C('APP_URL') . '/meetings/show?id=' . $id ;
                $type = 'edit';
                $this->template('Meetings/_email',
                    compact( 'user', 'room', 'url', 'post', 'count', 'host', 'recorder', 'type', 'join', 'joinCount'))
                    ->subject('[会议]《' . $old['title'] . '》会议修改')
                    ->to($joins)->cc([
                        ['name' => $session['nickname'], 'email' => $session['email']]
                    ])->send();

                $this->api['data']['id'] = $id;

            } else {//新增时入口

                //防止会议时间冲突
                $type = D('Meetings')->inquireAllTime($rooms,$post['start_time'],$post['end_time']);
                if ($type[0] == 1) throw new Exception('会议时间冲突，该时间段已有其他会议被预约');

                $post['user_id'] = $session['id'];
                $post['created_at'] = $now_time;

                //附件转换为数组形式
                $i = 0;
                foreach ($post['files'] as &$file) {
                    $meeting_files[$i]['path'] = $file['path'];
                    $meeting_files[$i]['ext'] = $file['ext'];
                    $meeting_files[$i]['name'] = $file['name'];
                    $meeting_files[$i]['savename'] = $file['savename'];
                    $i++;
                }
                $post['meeting_files'] = json_encode($meeting_files);  //转为json格式存储

                $id = M('Meetings')->add($post);

                $post['end'] = D('Meetings')->changeTime($post['end_time'],2);
                //写入通知中心(通知所有参会人员有一个会议)
                $participants = explode(',',$post['participants']);
                foreach ($participants as &$participant)
                {
                    M('Messages')->add([
                        'title' => '[会议]《' . $post['title'] . '》会议申请',
                        'abstract' => $user['name'] . '申请了' . $post['start_time'] . ' 至 ' . $post['end'] . ' 《' . $post['title'] . '》的会议，请你准时参加',
                        'module_name' => 'meetings',
                        'url' => '/meetings/show?id=' . $id,
                        'created_at' => time(),
                        'created_user' => $session['id'],
                        'target_user' => $participant,
                    ]);
                }

                //写入待办事项(给纪要员一个待办事项，通知他按时写入会议纪要)
                M('Todolist')->add([
                    'from_user_id' => $session['id'],
                    'who' => $post['recorder'],
                    'module' => 'meetings',
                    'matter_name' => '[会议] ' . '请在《' . $post['title'] . '》的会议结束后及时写入相关会议纪要',
                    'url' => C('WEB_SITE') . '/meetings/show?id=' . $id,
                    'generate_time' => time()
                ]);

                //申请会议时邮件通知
                $url = C('APP_URL') . '/meetings/show?id=' . $id ;
                $type = 'create';
                $this->template('Meetings/_email',
                    compact('user', 'room', 'url', 'post', 'count', 'host', 'recorder', 'type', 'join', 'joinCount'))
                    ->subject('[会议]《' . $post['title'] . '》会议申请')
                    ->to($joins)->cc([
                        ['name' => $session['nickname'], 'email' => $session['email']]
                    ])->send();

                $this->api['data']['id'] = $id;
            }

            M()->commit(); //提交事务

        } catch (Exception $exception) {
            M()->rollback();  //回退事务
            $this->api['code'] = 1;
            $this->api['msg'] = $exception->getMessage();
        }

        $this->ajaxReturn($this->api);
    }

    //meeting的取消接口
    public function destroyMeeting()
    {
        try {
            if (!IS_POST) throw new Exception('非法请求');

            M()->startTrans();
            $now_time = Carbon::now()->toDateTimeString(); //当前时间
            $session = session('user');

            $id = I('post.id');
            $post = M('Meetings')->find($id);
            $post['status'] = -1;
            $post['updated_at'] = $now_time;  //取消时间
            $post['updated_user_id'] = $session['id'];  //取消操作人id
            M('Meetings')->save($post); //将该会议状态改为-1


            $post['start_time'] = D('Meetings')->changeTime($post['start_time'],3);
            $post['end'] = D('Meetings')->changeTime($post['end_time'],2);

            //删除该会议纪要员的待办事项
            $head = C('WEB_SITE');
            M('Todolist')->where("url = '{$head}/meetings/show?id={$id}' ")->delete();

            //通知参会人员会议已经取消(通知消息)
            $participants = explode(',',$post['participants']);
            foreach ($participants as &$participant)
            {
                M('Messages')->add([
                    'title' => '[会议]《' . $post['title'] . '》会议取消',
                    'abstract' => '原计划将在 ' .  $post['start_time'] . ' 至 ' . $post['end'] . ' 开始的《' . $post['title'] . '》的会议已经取消了，请你知悉。',
                    'module_name' => 'meetings',
                    'url' => '/meetings/show?id=' . $id,
                    'created_at' => time(),
                    'created_user' => $session['id'],
                    'target_user' => $participant,
                ]);
            }

            //邮件信息
            $joins = D('User')->scope('basic')->field(['id', 'nickname' => 'name', 'email'])
                ->where("`id` in ({$post['participants']}) and `id`<>{$session['id']}")->select();
            $join = D('User')->scope('basic')->field(['id', 'nickname' => 'name', 'email'])
                ->where("`id` in ({$post['participants']})")->select();
            $joinCount = count($join);
            $user = M('User')->field(['id', 'nickname' => 'name'])->find($session['id']);
            $host = M('User')->field(['id', 'nickname' => 'name'])->find($post['host']);   //主持人
            $recorder = M('User')->field(['id', 'nickname' => 'name'])->find($post['recorder']);   //纪要员
            $room = M('MeetingRooms')->field(['name'])->where("id in ({$post['meeting_room_id']})")->select(); //会议室
            $count = count($room); //会议室个数
            //取消会议时邮件通知
            $url = C('APP_URL') . '/meetings/show?id=' . $id ;
            $type = 'del';
            $this->template('Meetings/_email',
                compact('user', 'url', 'post', 'host', 'recorder', 'room', 'count' , 'type', 'join', 'joinCount'))
                ->subject('[会议]《' . $post['title'] . '》会议取消')
                ->to($joins)->cc([
                    ['name' => $session['nickname'], 'email' => $session['email']]
                ])->send();

            $this->api['data']['id'] = $id;

            M()->commit(); //提交事务

        } catch (Exception $exception) {
            M()->rollback();
            $this->api['code'] = 1;
            $this->api['msg'] = $exception->getMessage();
        }

        $this->ajaxReturn($this->api);
    }

    //meetingRoom的保存编辑接口
    public function meetingRoomStore()
    {
        try {
            if (!IS_POST) throw new Exception('非法请求');
            $post = I('post.');
            $now_time = Carbon::now()->toDateTimeString(); //当前时间

            if (isset($post['id'])) {   //编辑
                $id = $post['id'];
                $post['updated_at'] = $now_time;
                $id = M('MeetingRooms')->save($post);
            } else {
                //新增
                $post['user_id'] = session('user')['id'];
                $post['created_at'] = $now_time;
                $id = M('MeetingRooms')->add($post);
            }

            $this->api['data']['id'] = $id;
        } catch (Exception $exception) {
            $this->api['code'] = 1;
            $this->api['msg'] = $exception->getMessage();
        }

        $this->ajaxReturn($this->api);
    }

    //meetingRoom的删除接口
    public function destroyMeetingRoom()
    {
        try {
            if (!IS_POST) throw new Exception('非法请求');
            $id = I('post.id');

            $now_time = Carbon::now()->toDateTimeString(); //当前时间
            $map = "find_in_set({$id},meeting_room_id) and end_time >= '{$now_time}'";
            $temp = M('Meetings')->field(['id','end_time'])->where($map)->select();
            if (!empty($temp)) throw new Exception('该会议室还有已预约的会议，不能删除!');

//            M('MeetingRooms')->delete($id);
            $data['id'] = $id;
            $data['status'] = 1;
            M('MeetingRooms')->save($data);
        } catch (Exception $exception) {
            $this->api['code'] = 1;
            $this->api['msg'] = $exception->getMessage();
        }

        $this->ajaxReturn($this->api);
    }

    //meetingRoom的图片上传接口
    public function uploadMeetingRoomPic()
    {
        $key = 'file';
        $config = [
            'rootPath' => './Uploads/',
            'maxSize' => 10485760,
            'savePath' => 'Meetings/Rooms/',
            'autoSub' => false,
            'exts' => ['jpg', 'jpeg', 'png'],
            'saveName' => time() . '_' . uniqid() . '_' . generateRandomString(),
        ];

        $uploader = new Upload($config);
        $result = $uploader->upload();

        if ($result) {
            $path = C('APP_URL') . '/Uploads/'.$result[$key]['savepath'].$result[$key]['savename'];
            $name = $result[$key]['name'];
            $savename = $result[$key]['savename'];
            //strtolower() 函数把字符串转换为小写。
            $ext = strtolower($result[$key]['ext']);
            $mime = $result[$key]['type'];
            $size = $result[$key]['size'];
            $time = time();

            //getchwd() 函数返回当前工作目录
            $source = getcwd() . '/Uploads/'.$result[$key]['savepath'].$result[$key]['savename'];

            // 裁剪图像
            FileUploadHandler::crop($source, 260, 190, $source);

            $data = [
                'code' => 0,
                'data' => [
                    'path' => $path,
                    'name' => $name,
                    'savename' => $savename,
                    'ext' => $ext
                ]
            ];
        } else {
            $data = [
                'code' => 1,
                'msg' => $uploader->getError()
            ];
        }

        $this->ajaxReturn($data);
    }
}